﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Mapping.ByCode;
using Xenta.Enums;
using Xenta.Utils;

namespace Xenta.Entities
{
    /// <summary>
    /// Represents the order item entity.
    /// </summary>
    /// <remarks><pre>
    /// The entity regarding the disclosure level.
    /// 
    /// + Entire
    ///  + Extended
    ///   | - Attributes(of the Extended level)
    ///   + Base
    ///    | - Order(of the Primary level)
    ///    | - SKU
    ///    | - Price
    ///    | - Quantity
    ///    | - TaxAmount
    ///    | - DiscountAmount
    ///    | - Subtotal
    ///    | - Total
    ///    | - Flags
    ///    | - UpdatedOn
    ///    | - CreatedOn
    ///    + Keys
    ///     + Primary
    ///      | - EntityID
    /// 
    /// Note: upper level includes lower level.
    /// </pre></remarks>
    public class OrderItemEntity : AuditableEntity
    {
        #region Fields

        private ICollection<OrderItemAttributeEntity> _attributes;
        private ICollection<SalesRuleHistoryEntity> _appliedRules;

        #endregion

        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public OrderItemEntity()
        {
            _attributes = new List<OrderItemAttributeEntity>();
            _appliedRules = new List<SalesRuleHistoryEntity>();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the order.
        /// </summary>
        public virtual OrderEntity Order
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the stock-keeping unit.
        /// </summary>
        public virtual string SKU
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the price.
        /// </summary>
        public virtual decimal Price
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the quantity.
        /// </summary>
        public virtual decimal Quantity
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the tax amount.
        /// </summary>
        public virtual decimal TaxAmount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the discount amount.
        /// </summary>
        public virtual decimal DiscountAmount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the subtotal.
        /// </summary>
        public virtual decimal Subtotal
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the total.
        /// </summary>
        public virtual decimal Total
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public virtual OrderItemFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Collections

        /// <summary>
        /// Gets or sets the collection of attributes.
        /// </summary>
        public virtual ICollection<OrderItemAttributeEntity> Attributes
        {
            get
            {
                return _attributes;
            }
            set
            {
                _attributes = value;
            }
        }

        /// <summary>
        /// Gets or sets the collection of applied sales rules.
        /// </summary>
        public virtual ICollection<SalesRuleHistoryEntity> AppliedRules
        {
            get
            {
                return _appliedRules;
            }
            set
            {
                _appliedRules = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets the attribute value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>The attribute value.</returns>
        public virtual string Attribute(string key)
        {
            if(String.IsNullOrWhiteSpace(key))
                return String.Empty;
            var attribute = _attributes.SingleOrDefault(x => x.Key.Equals(key));
            if(attribute == null)
                return String.Empty;
            return attribute.Value;
        }

        /// <summary>
        /// Gets the attribute value as the type T.
        /// </summary>
        /// <typeparam name="T">The type to return.</typeparam>
        /// <param name="key">The attribute key.</param>
        /// <returns>The attribute value as the type T.</returns>
        public virtual T Attribute<T>(string key)
        {
            return StringHelper.ParseAs<T>(Attribute(key));
        }

        #endregion

        #region Utilities

        protected override void Disclose(IDictionary<String, Object> obj,
            DisclosureLevel level,
            IDictionary<String, String> options)
        {
            base.Disclose(obj, level, options);
            if(level >= DisclosureLevel.Base)
            {
                obj["Order"] = Order.Disclose(DisclosureLevel.Primary, options);
                obj["SKU"] = SKU;
                obj["Price"] = Price;
                obj["Quantity"] = Quantity;
                obj["TaxAmount"] = TaxAmount;
                obj["DiscountAmount"] = DiscountAmount;
                obj["Subtotal"] = Subtotal;
                obj["Total"] = Total;
                obj["Flags"] = Flags.ToString();
            }
            if(level >= DisclosureLevel.Extended)
                obj["Attributes"] = Attributes.Map(x => x.Disclose(DisclosureLevel.Extended, options));
        }

        #endregion
    }

    /// <summary>
    /// The entity NHibernate mapping.
    /// </summary>
    public class OrderItemMapping : EntityMapping<OrderItemEntity>
    {
        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public OrderItemMapping()
        {
            Table("fwk_OrderItems");
            Id(x => x.EntityID, m =>
            {
                m.Column("ItemID");
                m.Generator(Generators.Identity);
            });
            ManyToOne(x => x.Order, m =>
            {
                m.Column("OrderID");
                m.ForeignKey("FK_fwk_OrderItems_fwk_Orders");
                m.NotNullable(true);
                m.Fetch(FetchKind.Join);
            });
            Property(x => x.SKU, m =>
            {
                m.NotNullable(true);
                m.Length(100);
                m.Column(c =>
                {
                    c.SqlType("nvarchar(100)");
                });
            });
            Property(x => x.Price, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.Quantity, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.TaxAmount, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.DiscountAmount, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.Subtotal, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.Total, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.Flags, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.CreatedOn, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.UpdatedOn, m =>
            {
                m.NotNullable(true);
            });
            Bag(x => x.Attributes, m =>
            {
                m.Table("fwk_GenericAttributes");
                m.Key(k =>
                {
                    k.Column("HolderID");
                    k.NotNullable(true);
                });
                m.Inverse(true);
                m.BatchSize(10);
            },
            a =>
            {
                a.OneToMany();
            });
            Bag(x => x.AppliedRules, m =>
            {
                m.Table("fwk_SalesRuleHistory");
                m.Key(k =>
                {
                    k.Column("ItemID");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.OneToMany();
            });
        }
    }
}
